In [18]:
%matplotlib inline
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
#add some edges with weights
G.add_edge(1,2, weight=15)
G.add_edge(1,3,weight=1)
G.add_edge(1,4,weight=2)
G.add_edge(1,6,weight=18)
G.add_edge(2,4,weight=1)
G.add_edge(2,5,weight=3)
G.add_edge(2,6,weight=2)
G.add_edge(3,5,weight=8)
G.add_edge(3,6,weight=1)
G.add_edge(4,5,weight=2)
G.add_edge(5,4,weight=3)
G.add_edge(5,6,weight=3)
G.add_edge(6,7,weight=1)
G.add_edge(7,2,weight=1)
#visualize this graph
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,node_size=700,node_color='b')
nx.draw_networkx_labels(G, pos, font_size=20)
nx.draw_networkx_edges(G,pos,edge_color='r',arrow=True)
plt.axis('off')
plt.savefig("weighted_digraph.png") # save as png
plt.show() # display
In [19]:
nx.dijkstra_path(G,1,5,weight='weight')
Out[19]:
In [21]:
nx.dijkstra_path(G,1,7,weight='weight')
Out[21]:
In [22]:
nx.single_source_dijkstra_path(G,1,weight='weight')
Out[22]:
In [25]:
nx.all_pairs_dijkstra_path(G,weight='weight')
Out[25]:
In [26]:
nx.floyd_warshall(G,weight='weight')
Out[26]:
In [27]:
nx.bellman_ford(G,1,weight='weight')
Out[27]:
In [67]:
nx.betweenness_centrality(G,k=None,weight='weight')
Out[67]:
Problem 2 : Write your own function to compute betweenness centrality of a node